
#include <BRender>
#include <BCamera>
#include <BTexture>

#include <BBillboard>
#include "member_BBillboard.h"

using namespace BWE;

#define member					(*(member_BBillboard*)_ptr)
#define member_allocate()		_ptr = new member_BBillboard
#define member_release()		delete (member_BBillboard*)_ptr

BBillboard::BBillboard()
{
	member_allocate();
}
BBillboard::BBillboard(BImage* image)
{
	member_allocate();
	this->setImage(image);
}
BBillboard::BBillboard(float width, float height)
{
	member_allocate();
	this->setWidth(width);
	this->setHeight( height);
}
BBillboard::BBillboard(BImage* image, float width, float height)
{
	member_allocate();
	this->setImage(image);
	this->setWidth(width);
	this->setHeight(height);
}
BBillboard::~BBillboard()
{
	member_release();
}

void BBillboard::setWidth(float width)
{
	if(member.width != width)
	{
		member.width = width;
	}
}
void BBillboard::setHeight(float height)
{
	if(member.height != height)
	{
		member.height = height;
	}
}

void BBillboard::setImage(BImage* image)
{
	if (member.image != image)
	{
		member.image = image;
	}
}
BImage* BBillboard::image()
{
	return member.image;
}
const BImage* BBillboard::image() const
{
	return member.image;
}

void BBillboard::around(BSpace& space) const
{
	float hh = member.height * 0.5f;
	float hw = member.width * 0.5f;
	space.min().set(-hw, -hh, 0);
	space.max().set(hw, hh, 0);
}
void BBillboard::render(BRender& render)
{
	BMatrix matrix = this->matrix();
	matrix.inverse();

	BCamera* camera = render.camera();
	BVector vec = camera->position() * matrix - this->position();
	vec.normalize();
	BVector vec_xz = BVector(vec.x(), 0, vec.z());
	vec_xz.normalize();
	BVector vec_xy = BVector(vec.x(), vec.y(), 0);
	vec_xy.normalize();
	float angleX = vec_xz.angle(BVector(1, 0, 0));
	float angleY = vec_xy.angle(BVector(1, 0, 0));

	render.setTexture(member.image);

	BVector v0(-member.width * 0.5f, -member.height * 0.5f, 0);
	BVector v1(member.width * 0.5f, -member.height * 0.5f, 0);
	BVector v2(member.width * 0.5f, member.height * 0.5f, 0);
	BVector v3(-member.width * 0.5f, member.height * 0.5f, 0);
	render.drawQuad(v0, v1, v2, v3);

	render.setTexture(0);
}

